package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("当前线程未：{}",Thread.currentThread().getId());//在同一次请求中线程id是一样的
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();//获取当前路径（除开网络三要素）
        log.info("当前路径"+requestURI);
        String[] urls = new String[]{//需要放行的资源，不需要处理的
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
        };
        boolean check = check(urls, requestURI);//为true表示当前路径之间放行
        if (check){
            filterChain.doFilter(request, response);
            return;
        }
        //此时为false，说明没在当前放行的路径下，此时就需要看是否存在session对象了,存在则放行，不存在则不放行
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId!=null){
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId!=null){
            BaseContext.setCurrentId(userId);
            log.info("当前用户的与线程：{}，绑定的id{}",Thread.currentThread(),BaseContext.getCurrentId() );
            filterChain.doFilter(request, response);
            return;
        }

        //解决乱码
        response.setCharacterEncoding("UTF-8");
        //如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
